package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.stock.service.IStockService;
import cn.tedu.csmall.stock.webapi.until.BlockErrorHandler;
import cn.tedu.csmall.stock.webapi.until.FallbackErrorHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/base/stock")
@Api(tags = "库存管理")
public class StockController {

    @Autowired
    private IStockService stockService;
   //http://localhost:20003/base/stock/reduce/count  StockReduceCountDTO
    //    JSON
    @PostMapping("/reduce/count")
    @ApiOperation("减少商品库存数")
    @SentinelResource(value = "减少库存的方法",
    blockHandlerClass = BlockErrorHandler.class , blockHandler = "blockError",
    fallbackClass = FallbackErrorHandler.class, fallback ="fallbackError" )
    public JsonResult reduceCommodityCount(
            @RequestBody StockReduceCountDTO stockReduceCountDTO){
//        0---1  <0.5 true
        if (Math.random()<0.5){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"随机抛出异常");
        }
        // 调用业务逻辑层
        stockService.reduceCommodityCount(stockReduceCountDTO);
        return JsonResult.ok("商品库存减少完成!");
    }


}
